package com.atguigu.gmall.common.rabbit.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.rabbit.model.GmallCorrelationData;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2023-05-08 14:43
 */
@Component
public class RabbitService {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用于生产者发送消息方法
     */
    public void sendMessage(String exchange, String routingKey, Object msg) {
        //调用模板对象发送消息
        //1.构建相关数据,将相关数据存入Redis
        GmallCorrelationData correlationData = new GmallCorrelationData();
        //相关数据唯一标识
        String uuid = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(uuid);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(msg);
        //存入redis
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData), 1, TimeUnit.HOURS);
        //2.发送消息时候 选择既有业务消息还包括相关消息
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, correlationData);
    }


    /**
     * 用于生产者发送延迟消息方法
     */
    public void sendDelayMessage(String exchange, String routingKey, Object msg, Integer ttlTime) {
        //调用模板对象发送消息
        //1.构建相关数据,将相关数据存入Redis
        GmallCorrelationData correlationData = new GmallCorrelationData();
        //相关数据唯一标识
        String uuid = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(uuid);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setMessage(msg);
        //存入redis
        correlationData.setDelay(true);
        correlationData.setDelayTime(ttlTime);
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData), ttlTime + 600, TimeUnit.SECONDS);
        //2.发送消息时候 选择既有业务消息还包括相关消息  通过参数四消息后置处理器,改写消息属性.为消息设置TTL时间
        rabbitTemplate.convertAndSend(exchange, routingKey, msg, (message)->{
            //为消息改写延迟时间
            message.getMessageProperties().setDelay(ttlTime*1000);
            return message;
        }, correlationData);
    }
}
